<?php


namespace app\web\controller;

use app\api\validate\ViperCard as ViperCardValidate;
use app\common\constant\TemplateConstant;
use app\common\controller\Alisms;
use app\common\helper\FormatHelper;
use app\common\model\ViperMoneyLog;
use app\common\model\ViperUser;
use app\common\model\ViperCard as ViperCardModel;
use app\common\service\CommonService;
use app\common\controller\Smscm;
use app\common\service\FeiEPrintService;
use app\common\service\TicketService;
use app\common\service\ViperCardService;
use app\user\model\User;
use think\Db;
use think\Exception;
use app\common\model\ViperCardRechargeLog;
use think\Validate;

/**
 * 会员卡首页控制器
 * @package app\index\controller
 */
class ViperCard extends Auth
{
    public $noNeedLogin = '';

    /**
     * 会员卡开卡
     */
    public function add()
    {
        $data = $this->request->post();

        $validate = new ViperCardValidate();
        if (!$validate->check($data)) {
            $this->result($validate->getError(), '', 204);
        }
        $amount = 0;
        $give_amount = 0;
        switch ($data['template_type']) {
            case TemplateConstant::TEMPLATE_TYPE_DEFAULT ://会员卡
                $data['recharge_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_NUMBER ://次卡
                $data['number_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_MONTH ://月卡
                $data['month_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_AMOUNT ://实际金额充值
                $amount = $data['amount'];
                $give_amount = $data['give_amount'];
                break;
        }


        $user = ViperUser::where(['phone' => $data['mobile']])->find();
        $temp_arr = [
            'mobile' => $data['mobile'],
            'card_no' => $data['card_no'],
            'viper_user_id' => !empty($user['id']) ? $user['id'] : 0,
            'user_id' => $this->userInfo['id'],
            'is_receiver_message' => $data['is_receiver_message'],
            'name' => $data['name'],
            'gender' => $data['gender'],
            'sale_id' => $data['sale_id'],
            'type' => $data['type'],
            'viper_type_id' => $data['viper_type_id'],
            'birthday' => strtotime($data['birthday']),
            'pay_content' => $data['pay_content'],
            'neima' => $data['neima'],
            'store_id' => $this->userInfo['store_id'],
            'amount' => $amount,
            'payee' => $this->userInfo['store_id'],
            'total_amount' => $amount,
            'give_amount' => $give_amount,
            'give_total_amount' => $give_amount,
            'open_content' => $data['open_content'],
            'template_id' => $data['template_id'],
            'template_type' => $data['template_type'],
            'sales_person_data' => $data['sales_person_data'] ?? '',
        ];

        ViperCardModel::openCard($temp_arr, $this->userInfo);

        $this->result('操作成功', '', 200);
    }


    /**
     * 会员卡充值
     *
     * TODO 充值金额，后端需要再计算一下
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recharge()
    {
        $post = $this->request->post();
        $rule = [
            'viper_card_id' => 'require',
            'template_id' => 'require',
            'template_type' => 'require',
        ];
        $message = [
            'viper_card_id.require' => '会员卡ID不能为空',
            'template_id.mobile' => '充值模版不能为空',
            'template_type.require' => '充值类型不能为空',
        ];
        $validate = new Validate($rule, $message);
        if (!$validate->check($post)) {
            $this->result($validate->getError(), '', 204);
        }
        $card_res = Db::name('qt_viper_card')->where('id', $post['viper_card_id'])->find();
        if (empty($card_res)) {
            $this->result('会员卡不存在', '', 204);
        }
        if($card_res['status'] != '1'){
            $this->result('会员卡已经挂失或者删除了', '', 204);
        }

        //多人总提成
        $is_many_people_commission = false;
        if(isset($post['sales_person_data'])){
            $post['sales_person_data'] = json_decode($post['sales_person_data'],true);
        }
        if (!empty($post['sales_person_data'])) {
            $is_many_people_commission = true;
            $sales_person_data = $post['sales_person_data'];
            $many_people_commission =  array_sum(array_column($sales_person_data['list'],'commission'));
            $sale_id =  implode(',',array_column($sales_person_data['list'],'commission_user_id'));
            $group_id =  implode(',',array_column($sales_person_data['list'],'group_id'));

        }else {
           $sale_id = !empty($post['sale_id']) ? $post['sale_id'] : 0;
           $group_id = !empty($sale_id) ? Db::name('qt_users')->where('id',$sale_id)->value('group') : 0;
        }


        if ($post['template_type'] == TemplateConstant::TEMPLATE_TYPE_DEFAULT) {
            $template_res = Db::name('qt_viper_recharge_template')->where('id', $post['template_id'])->find();
            //$userViper = Db::name('qt_user_viper')->where('id', $card_res['user_id'])->find();
            //判断是否有返还金额
            $give_amount = ViperCardModel::returnAmount($post['viper_card_id'], $post['template_id']);
            $insert = [
                'store_id' => $this->userInfo['store_id'],//门店
                'after_money' => $card_res['amount'],//会员充值余额
                'viper_card_id' => $post['viper_card_id'],//会员卡id
                'amount' => $template_res['amount'],//充值金额
                'give_amount' => $give_amount,//赠送金额
                'after_amount' => $card_res['amount'],//充值之前金额
                'recharge_temp_name' => $template_res['name'],//充值模板名称
                'recharge_tempid' => $template_res['id'],//充值模板id
                'pay_status' => 1,//支付状态 0 未支付 1 正常 3 已撤销
                'pay_time' => time(),//支付时间
                'order_no' => create_card_recharge(),//支付单号
                'pay_content' => $post['pay_content'],//支付方式 1 微信 2 支付宝
                'integral' => $template_res['integral'],//赠送的积分数量
                'type' => 2,//卡片状态 1开卡 2 充值
                'card_amount' => $template_res['amount'] + $give_amount,//入卡金额
                'sale_id' => $sale_id,//销售人
                'commission' => $is_many_people_commission == true ? $many_people_commission : $template_res['rate'],//提成
                'payee' => $this->userInfo['id'],//收款人
                'collection_time' => time(),//收款时间
                'card_type' => TemplateConstant::TEMPLATE_TYPE_DEFAULT,//卡片类型：1充值，2次卡，3 月卡
                'is_first' => 2,//1 首充 2 续充
                'recharge_content' => $post['recharge_content'],//充值备注
                'creater' => $this->userInfo['id'],
                'updater' => $this->userInfo['id'],
                'create_time' => time(),
                'update_time' => time(),
                'group_id' => $group_id,
                'many_people_commission' => $is_many_people_commission == true ? json_encode($post['sales_person_data'],JSON_UNESCAPED_UNICODE) : '',
            ];
            //更新会员卡数据
            $viper_card = [
                'amount' => $card_res['amount'] + $template_res['amount'],//充值金额
                'give_amount' => $card_res['give_amount'] + $give_amount,//赠送金额
                'give_total_amount' => $card_res['give_total_amount'] + $give_amount,//总赠送金额
                'total_amount' => $card_res['total_amount'] + $template_res['amount'],//总充值金额
                'score' => $card_res['score'] + $template_res['integral'],//积分
            ];
            //$user = [
            //    'money' => $userViper['money'] + $template_res['amount'],
            //    'integral' => $userViper['integral'] + $template_res['integral'],
            //];

            Db::startTrans();

            try {

                //插入日志
                $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
                //更新会员卡
                Db::name('qt_viper_card')->where('id', $post['viper_card_id'])->update($viper_card);

                check_out_pay_all($post['pay_content'], $recharge_log_id, $this->userInfo, '1',0,0,$post['viper_card_id']);

                //写提成记录,是否多人提成
                if ($is_many_people_commission == true) {

                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    //$commission_data['saler_id'] = array_column($sales_person_data,'commission_user_id');//销售人
                    ViperCardModel::rechargeCommissionMany($commission_data, $recharge_log_id, $post['viper_card_id'], 4,'2');

                }else {
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    $commission_data['sale_id'] = !empty($post['sale_id']) ? $post['sale_id'] : 0;
                    ViperCardModel::rechargeCommission($commission_data, $recharge_log_id, $post['viper_card_id'], 4,'2');
                }


                //资金变动记录
                ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$template_res['amount'],'1','1',($card_res['amount'] + $template_res['amount']));
                //赠送金额变动记录
                if($give_amount != 0){
                    ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$give_amount,'1','3',($card_res['give_total_amount'] + $give_amount));
                }
                //积分变动记录
                if($template_res['integral'] != 0){
                    ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$give_amount,'1','2',($card_res['score'] + $template_res['integral']));
                }

                //打印普通充值单
                FeiEPrintService::printPhoneEntry(['viper_card_id' => $post['viper_card_id'], 'recharge_log_id' => $recharge_log_id], $this->userInfo);

                //发送短信
                Alisms::rechargeSend($recharge_log_id);

                //处理优惠券
                if (!empty($post['coupon'])) {
                    $coupon = json_decode($post['coupon'], true);
                    TicketService::sendTicket($coupon, $this->userInfo, $card_res);

                    $coupon_name = array_column($coupon, 'name');
                    Db::name('qt_viper_card_recharge_log')->where('id', $recharge_log_id)->update(['coupon_name' => implode(',', $coupon_name)]);
                }

                ViperCardModel::saveMoneyLog($post['viper_card_id'], $insert['card_amount']);//资金变动记录

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('充值失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
            }
        }
        //次卡充值
        if ($post['template_type'] == TemplateConstant::TEMPLATE_TYPE_NUMBER) {
            $template_res = Db::name('qt_viper_number_card_template')->where('id', $post['template_id'])->find();
            $totalNumber = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$post['template_id']])->value('number');
            $insert = [
                'store_id' => $this->userInfo['store_id'],//门店
                'after_money' => $card_res['amount'],//会员充值余额
                'viper_card_id' => $post['viper_card_id'],//会员卡id
                'amount' => $template_res['amount'],//充值金额
                'give_amount' => 0,//赠送金额
                'after_amount' => $card_res['amount'],//充值之前金额
                'recharge_temp_name' => $template_res['name'],//充值模板名称
                'recharge_tempid' => $template_res['id'],//充值模板id
                'pay_status' => 1,//支付状态 0 未支付 1 正常 3 已撤销
                'pay_time' => time(),//支付时间
                'order_no' => create_card_recharge(),//支付单号
                'pay_content' => $post['pay_content'],//支付方式 1 微信 2 支付宝
                'integral' => 0,//赠送的积分数量
                'type' => 2,//卡片状态 1开卡 2 充值
                'card_amount' => $template_res['amount'],//入卡金额
                //'sale_id' => !empty($post['sale_id']) ? $post['sale_id'] : 0,//销售人
                //'commission' => $template_res['rate'],//提成
                'sale_id' => $sale_id,//销售人
                'commission' => $is_many_people_commission == true ? $many_people_commission : $template_res['rate'],//提成
                'payee' => $this->userInfo['id'],//收款人
                'collection_time' => time(),//收款时间
                'card_type' => TemplateConstant::TEMPLATE_TYPE_NUMBER,//卡片类型：1充值，2次卡，3 月卡
                'is_first' => 2,//1 首充 2 续充
                'recharge_content' => $post['recharge_content'],//充值备注
                'creater' => $this->userInfo['id'],
                'updater' => $this->userInfo['id'],
                'create_time' => time(),
                'update_time' => time(),
                'group_id' => $group_id,
                'many_people_commission' => $is_many_people_commission == true ? json_encode($post['sales_person_data'],JSON_UNESCAPED_UNICODE) : '',

            ];

            //$user = [
            //    'money'=>$userViper['money'] + $template_res['amount'],
            //    'integral'=>$userViper['integral'] + $template_res['integral'],
            //];
            Db::startTrans();

            try {
                //插入日志
                $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
                $viper_card_item = [
                    'viper_card_id' => $post['viper_card_id'],
                    'recharge_template_id' => '',
                    'month_template_id' => '',
                    'number_template_id' => $post['template_id'],
                    'recharge_log_id' => $recharge_log_id,
                    'total_number' => $totalNumber,
                ];
                //更新会员卡
                Db::name('qt_viper_card_item')->insert($viper_card_item);
                //更新用户
                //Db::name('qt_user_viper')->where('id',$card_res['user_id'])->update($user);

                check_out_pay_all($post['pay_content'], $recharge_log_id, $this->userInfo, '1',0,0,$post['viper_card_id']);

                //打印普通充值单
                FeiEPrintService::printPhoneEntry(['viper_card_id' => $post['viper_card_id'], 'recharge_log_id' => $recharge_log_id], $this->userInfo);

                //写提成记录,是否多人提成
                if ($is_many_people_commission == true) {
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    //$commission_data['saler_id'] = array_column($sales_person_data,'commission_user_id');//销售人
                    ViperCardModel::rechargeCommissionMany($commission_data, $recharge_log_id, $post['viper_card_id'], 5,'2');

                }else {
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    $commission_data['sale_id'] = !empty($post['sale_id']) ? $post['sale_id'] : 0;
                    ViperCardModel::rechargeCommission($commission_data, $recharge_log_id, $post['viper_card_id'], 5,'2');
                }

                ViperCardModel::saveMoneyLog($post['viper_card_id'], $insert['card_amount']);//资金变动记录
                //发送短信
                Alisms::rechargeSend($recharge_log_id);

                //处理优惠券
                if (!empty($post['coupon'])) {
                    $coupon = json_decode($post['coupon'], true);
                    TicketService::sendTicket($coupon, $this->userInfo, $card_res);

                    $coupon_name = array_column($coupon, 'name');
                    Db::name('qt_viper_card_recharge_log')->where('id', $recharge_log_id)->update(['coupon_name' => implode(',', $coupon_name)]);

                }

                Db::commit();

            } catch (Exception $exception) {
                Db::rollback();
                $this->result('充值失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
            }
        }

        //月卡充值
        if ($post['template_type'] == TemplateConstant::TEMPLATE_TYPE_MONTH) {
            $template_res = Db::name('qt_viper_month_card_template')->where('id', $post['template_id'])->find();
            $insert = [
                'store_id' => $this->userInfo['store_id'],//门店
                'after_money' => $card_res['amount'],//会员充值余额
                'viper_card_id' => $post['viper_card_id'],//会员卡id
                'amount' => $template_res['amount'],//充值金额
                'give_amount' => 0,//赠送金额
                'after_amount' => $card_res['amount'],//充值之前金额
                'recharge_temp_name' => $template_res['name'],//充值模板名称
                'recharge_tempid' => $template_res['id'],//充值模板id
                'pay_status' => 1,//支付状态 0 未支付 1 正常 3 已撤销
                'pay_time' => time(),//支付时间
                'order_no' => create_card_recharge(),//支付单号
                'pay_content' => $post['pay_content'],//支付方式 1 微信 2 支付宝
                'integral' => 0,//赠送的积分数量
                'type' => 2,//卡片状态 1开卡 2 充值
                'card_amount' => $template_res['amount'],//入卡金额
                //'sale_id' => !empty($post['sale_id']) ? $post['sale_id'] : 0,//销售人
                //'commission' => $template_res['rate'],//提成
                'sale_id' => $sale_id,//销售人
                'commission' => $is_many_people_commission == true ? $many_people_commission : $template_res['rate'],//提成
                'payee' => $this->userInfo['id'],//收款人
                'collection_time' => time(),//收款时间
                'card_type' => TemplateConstant::TEMPLATE_TYPE_MONTH,//卡片类型：1充值，2次卡，3 月卡
                'is_first' => 2,//1 首充 2 续充
                'recharge_content' => $post['recharge_content'],//充值备注
                'creater' => $this->userInfo['id'],
                'updater' => $this->userInfo['id'],
                'create_time' => time(),
                'update_time' => time(),
                'group_id' => $group_id,
                'many_people_commission' => $is_many_people_commission == true ? json_encode($post['sales_person_data'],JSON_UNESCAPED_UNICODE) : '',

            ];
            //$user = [
            //    'money'=>$userViper['money'] + $template_res['amount'],
            //    'integral'=>$userViper['integral'] + $template_res['integral'],
            //];
            Db::startTrans();
            try {
                //插入日志
                $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
                $viper_card_item = [
                    'viper_card_id' => $post['viper_card_id'],
                    'recharge_template_id' => '',
                    'month_template_id' => $post['template_id'],
                    'number_template_id' => '',
                    'recharge_log_id' => $recharge_log_id,
                ];
                //更新会员卡
                Db::name('qt_viper_card_item')->insert($viper_card_item);

                //更新用户
                //Db::name('qt_user_viper')->where('id',$card_res['user_id'])->update($user);

                check_out_pay_all($post['pay_content'], $recharge_log_id, $this->userInfo, '1',0,0,$post['viper_card_id']);
                //发送短信
                Alisms::rechargeSend($recharge_log_id);

                //处理优惠券
                if (!empty($post['coupon'])) {
                    $coupon = json_decode($post['coupon'], true);
                    TicketService::sendTicket($coupon, $this->userInfo, $card_res);

                    $coupon_name = array_column($coupon, 'name');
                    Db::name('qt_viper_card_recharge_log')->where('id', $recharge_log_id)->update(['coupon_name' => implode(',', $coupon_name)]);

                }

                //写提成记录,是否多人提成
                if ($is_many_people_commission == true) {
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    //$commission_data['saler_id'] = array_column($sales_person_data,'commission_user_id');//销售人
                    ViperCardModel::rechargeCommissionMany($commission_data, $recharge_log_id, $post['viper_card_id'], 7,'2');

                }else {
                    //写提成记录
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    $commission_data['sale_id'] = !empty($post['sale_id']) ? $post['sale_id'] : 0;
                    ViperCardModel::rechargeCommission($commission_data, $recharge_log_id, $post['viper_card_id'], 7, '2');
                }
                //资金变动记录
                ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$post['amount'],'1','1',($card_res['amount'] + $post['amount']));
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('充值失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
            }
        }
        if ($post['template_type'] == TemplateConstant::TEMPLATE_TYPE_AMOUNT) {
            //自由充值
            //$userViper = Db::name('qt_user_viper')->where('id', $card_res['user_id'])->find();
            $post['give_amount'] = !empty($post['give_amount']) ? $post['give_amount'] : 0;
            $insert = [
                'store_id' => $this->userInfo['store_id'],//门店
                'after_money' => $card_res['amount'],//会员充值余额
                'viper_card_id' => $post['viper_card_id'],//会员卡id
                'amount' => $post['amount'],//充值金额
                'give_amount' => $post['give_amount'],//赠送金额
                'after_amount' => $card_res['amount'],//充值之前金额
                'recharge_temp_name' => '按实际金额充值',//充值模板名称
                'recharge_tempid' => 0,//充值模板id
                'pay_status' => 1,//支付状态 0 未支付 1 正常 3 已撤销
                'pay_time' => time(),//支付时间
                'order_no' => create_card_recharge(),//支付单号
                'pay_content' => $post['pay_content'],//支付方式 1 微信 2 支付宝
                'integral' => 0,//赠送的积分数量
                'type' => 2,//卡片状态 1开卡 2 充值
                'card_amount' => $post['amount'] + $post['give_amount'],//入卡金额
                //'sale_id' => !empty($post['sale_id']) ? $post['sale_id'] : 0,//销售人
                //'commission' => 0,//提成
                'sale_id' => $sale_id,//销售人
                'commission' => $is_many_people_commission == true ? $many_people_commission : 0,//提成
                'payee' => $this->userInfo['id'],//收款人
                'collection_time' => time(),//收款时间
                'card_type' => TemplateConstant::TEMPLATE_TYPE_AMOUNT,//卡片类型：1充值，2次卡，3 月卡
                'is_first' => 2,//1 首充 2 续充
                'recharge_content' => $post['recharge_content'],//充值备注
                'creater' => $this->userInfo['id'],
                'updater' => $this->userInfo['id'],
                'create_time' => time(),
                'update_time' => time(),
                'group_id' => $group_id,
                'many_people_commission' => $is_many_people_commission == true ? json_encode($post['sales_person_data'],JSON_UNESCAPED_UNICODE) : '',
            ];

            $viper_card = [
                'amount' => $card_res['amount'] + $post['amount'],
                'give_amount' => $card_res['give_amount'] + $post['give_amount'],
                'give_total_amount' => $card_res['give_total_amount'] + $post['give_amount'],
                'total_amount' => $card_res['total_amount'] + $post['amount'],
            ];
            Db::startTrans();
            try {
                //插入日志
                $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
                //更新会员卡
                Db::name('qt_viper_card')->where('id', $post['viper_card_id'])->update($viper_card);
                //插入支付方式
                check_out_pay_all($post['pay_content'], $recharge_log_id, $this->userInfo, '1',0,0,$post['viper_card_id']);

                //写提成记录,是否多人提成
                if ($is_many_people_commission == true) {
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    //$commission_data['saler_id'] = array_column($sales_person_data,'commission_user_id');//销售人
                    ViperCardModel::rechargeCommissionMany($commission_data, $recharge_log_id, $post['viper_card_id'], 4,'2');

                }else {
                    //写提成记录
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    $commission_data['sale_id'] = !empty($post['sale_id']) ? $post['sale_id'] : 0;
                    ViperCardModel::rechargeCommission($commission_data, $recharge_log_id, $post['viper_card_id'], 4,'2');
                }

                //资金变动记录
                ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$post['amount'],'1','1',($card_res['amount'] + $post['amount']));
                //赠送金额变动记录

                if($post['give_amount'] != 0){
                    ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$post['give_amount'],'1','3',($card_res['give_amount'] + $post['give_amount']));
                }
                //积分变动记录
                //if($template_res['integral'] != 0){
                //    ViperMoneyLog::moneyLog($post['viper_card_id'],$recharge_log_id,'1',$give_amount,'1','2',($card_res['score'] + $template_res['integral']));
                //}
                //发送短信
                Alisms::rechargeSend($recharge_log_id);
                //处理优惠券
                if (!empty($post['coupon'])) {
                    $coupon = json_decode($post['coupon'], true);
                    TicketService::sendTicket($coupon, $this->userInfo, $card_res);

                    $coupon_name = array_column($coupon, 'name');
                    Db::name('qt_viper_card_recharge_log')->where('id', $recharge_log_id)->update(['coupon_name' => implode(',', $coupon_name)]);
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('充值失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
            }
        }
        $this->result('充值成功', '', 200);

    }


    /**
     * 会员管理---会员卡列表
     * mobile  card_no
     */
    public function lists()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $sql = ViperCardModel::alias('v')
            ->field('v.id,v.name as user_name,v.mobile,v.card_no,v.amount,t.name,v.avatar,v.birthday,v.gender,v.is_receiver_message,v.amount,v.total_amount,v.give_total_amount,v.amount,v.give_amount,v.score,v.status,v.open_content,v.viper_type_id')
            ->leftJoin('dp_qt_viper_type t', 't.id=v.viper_type_id')
            ->leftJoin('dp_qt_user_viper uv', 'uv.id=v.viper_user_id')
            ->where(['v.store_id' => $this->userInfo['store_id']])
            ->where('v.status', '<>', '4');
        $where = [];
        //手机号搜索
        if (isset($data['mobile']) && !empty($data['mobile'])) {
            $sql = $sql->where(['v.mobile' => $data['mobile']]);
            $where['mobile'] = $data['mobile'];
        }
        //卡号搜索
        if (isset($data['card_no']) && !empty($data['card_no'])) {
            $sql = $sql->where(['v.card_no' => $data['card_no']]);
            $where['card_no'] = $data['card_no'];
        }
        //卡类型
        if (isset($data['viper_type_id']) && !empty($data['viper_type_id'])) {
            $sql = $sql->where(['v.viper_type_id' => $data['viper_type_id']]);
            $where['viper_type_id'] = $data['viper_type_id'];
        }
        //姓名搜索
        if (isset($data['name']) && !empty($data['name'])) {
            $sql = $sql->where(['v.name' => $data['name']]);
            $where['name'] = $data['name'];
        }
        //状态搜索
        if (isset($data['status']) && !empty($data['status'])) {
            $sql = $sql->where(['v.status' => $data['status']]);
            $where['status'] = $data['status'];
        }
        //绑定状态搜索
        if (isset($data['bind_status']) && !empty($data['bind_status'])) {
            $sql = $sql->where(['v.bind_status' => $data['bind_status']]);
            $where['bind_status'] = $data['bind_status'];
        }
        //开卡时间start_create_time
        if (!empty($data['start_create_time']) && !empty($data['end_create_time'])) {
            $start_time = strtotime($data['start_create_time']);
            $end_time = strtotime($data['end_create_time']);
            $sql = $sql->whereBetweenTime('v.create_time', $start_time, $end_time);
            $where['create_time'] = ['between',[$start_time,$end_time]];
        }
        //生日查询
        if (isset($data['start_birthday']) && !empty($data['start_birthday']) && isset($data['end_birthday']) && !empty($data['end_birthday'])) {
            $start_time = strtotime($data['start_birthday']);
            $end_time = strtotime($data['end_birthday']);
            $sql = $sql->whereBetweenTime('v.birthday', $start_time, $end_time);
        }
        //本金区间
        if (isset($data['start_amount']) && !empty($data['start_amount']) && isset($data['end_amount']) && !empty($data['end_amount'])) {
            $sql = $sql->whereBetween('v.amount', [$data['start_amount'], $data['end_amount']]);
            $where['amount'] = ['between',[$data['start_amount'],$data['end_amount']]];
        }

        //赠送金额
        if (isset($data['start_give_amount']) && !empty($data['start_give_amount']) && isset($data['end_give_amount']) && !empty($data['end_give_amount'])) {
            $sql = $sql->whereBetween('v.give_amount', [$data['start_give_amount'], $data['end_give_amount']]);
            $where['give_amount'] = ['between',[$data['start_give_amount'],$data['end_give_amount']]];
        }

        //充值总金额
        if (isset($data['start_total_amount']) && !empty($data['start_total_amount']) && isset($data['end_total_amount']) && !empty($data['end_total_amount'])) {
            $sql = $sql->whereBetween('v.total_amount', [$data['start_total_amount'], $data['end_total_amount']]);
            $where['total_amount'] = ['between',[$data['start_total_amount'],$data['end_total_amount']]];
        }
        //赠送总金额
        if (isset($data['start_give_total_amount']) && !empty($data['start_give_total_amount']) && isset($data['end_give_total_amount']) && !empty($data['end_give_total_amount'])) {
            $sql = $sql->whereBetween('v.give_total_amount', [$data['start_give_total_amount'], $data['end_give_total_amount']]);
            $where['give_total_amount'] = ['between',[$data['start_give_total_amount'],$data['end_give_total_amount']]];
        }
        $list = $sql->order('v.id desc')->paginate($data['limit'])->each(function ($item) {
            $item['avatar'] = get_img_path($item['avatar']);
            $numberCard = Db::name('qt_viper_card_item')
                ->field('ci.*,ti.number')
                ->alias('ci')
                ->leftJoin('qt_viper_number_card_template_item ti', 'ti.number_card_template_id = ci.number_template_id')
                ->where(['viper_card_id' => $item['id'], 'status' => '1'])
                ->select();
            $surplus = 0;
            foreach ($numberCard as $k => $v) {
                $use = Db::name('qt_viper_card_use_log')->where(['viper_card_id' => $item['id'], 'template_id' => $v['number_template_id'], 'card_type' => '1'])->count();
                $surplus += ($v['number'] - $use);
            }
            if ($surplus < 0) {
                $surplus = 0;
            }
            $item['surplus'] = $surplus;
            return $item;
        });
        $total['amount'] = Db::name('qt_viper_card')->where($where)->where(['store_id' => $this->userInfo['store_id'], 'status' => '1'])->sum('amount');
        $total['give_amount'] = Db::name('qt_viper_card')->where(['store_id' => $this->userInfo['store_id'], 'status' => '1'])->sum('give_amount');
        $total['score'] = Db::name('qt_viper_card')->where(['store_id' => $this->userInfo['store_id'], 'status' => '1'])->sum('score');
        $result['list'] = $list;
        $result['total'] = $total;
        $this->result('获取成功', $result, 200);
    }

    /**
     * 会员卡详情
     */
    public function detail()
    {
        $data = $this->request->post();

        if (empty($data['viper_card_id']))
            $this->result('缺少必要参数', '', 204);

        $info = ViperCardModel::get($data['viper_card_id']);

        $recharges = ViperCardRechargeLog::getLists($this->userInfo['id'], $data['viper_card_id'], 'id,amount,give_amount,create_time');

        foreach ($recharges as $key => $item) {

            $lists[$key]['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
        }

        $info['recharge'] = $recharges;

        $pays = ViperCardModel::getOrdersOfCard($this->userInfo['id'], $data['viper_card_id'], 'total_price,created_time');

        foreach ($pays as $key => $value) {
            $pays[$key]['cash_name'] = $this->userInfo['name'];
            $pays[$key]['cash_name'] = date('Y-m-d H:i:s', $data['created_time']);
        }

        $info['pay'] = $pays;

        $info['engineer'] = ViperCardModel::getEngineerOfCard($this->userInfo['id'], $data['viper_card_id']);

        $this->result('获取成功', $info, 200);

    }


    /**
     * 会员卡查询
     */
    public function search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['type']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            $sql = Db::name('qt_viper_card')
                ->field('vc.id,vc.viper_type_id,vc.avatar,vc.mobile,vc.birthday,vc.card_no,vc.viper_user_id,vc.neima,
                vc.amount,vt.name as type_name,vc.name,vc.create_time,vc.gender,vc.score,vc.amount,vc.status,vc.give_amount,
                s.name as store_name,vc.expire,vc.is_receiver_message,vc.open_content,vc.give_total_amount'
                )
                ->alias('vc')
                ->leftJoin('qt_viper_type vt', 'vc.viper_type_id = vt.id')
                ->leftJoin('qt_store s', 'vc.store_id = s.id')
                ->where('vc.status', '1');
            //手机号
            if ($getData['type'] == '1' && !empty($getData['phone'])) {
                if (strlen($getData['phone']) < 4) {
                    $this->result('手机号请最少输入四位数', '', 204);
                }
                $sql->whereLike('vc.mobile', '%' . $getData['phone'] . '%');
            } elseif ($getData['type'] == '2' && !empty($getData['card_no'])) {
                //卡号
                $sql->where('vc.card_no', $getData['card_no']);
            } else {
                $this->result('缺少参数', '', 204);
            }
            $data = $sql->select();
            foreach ($data as $key => $value) {
                $data[$key]['avatar'] = get_img_path($value['avatar']);
            }
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员卡挂失查询
     */
    public function close_search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['type']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            $sql = Db::name('qt_viper_card')
                ->field('vc.id,vc.viper_type_id,vc.avatar,vc.avatar,vc.mobile,
                vc.birthday,vc.card_no,vc.amount,vt.name as type_name,vc.name,
                vc.create_time,vc.gender,vc.score,vc.amount,vc.status,vc.neima,
                vc.give_amount,s.name as store_name,vc.expire,vc.is_receiver_message,
                vc.open_content,vc.give_total_amount')
                ->alias('vc')
                ->leftJoin('qt_viper_type vt', 'vc.viper_type_id = vt.id')
                ->leftJoin('qt_store s', 'vc.store_id = s.id');
            //手机号
            if ($getData['type'] == '1' && !empty($getData['phone'])) {
                if (strlen($getData['phone']) < 4) {
                    $this->result('手机号请最少输入四位数', '', 204);
                }
                $sql->whereLike('vc.mobile', '%' . $getData['phone'] . '%');
            } elseif ($getData['type'] == '2' && !empty($getData['card_no'])) {
                //卡号
                $sql->where('vc.card_no', $getData['card_no']);
            } else {
                $this->result('缺少参数', '', 204);
            }
            $data = $sql->select();
            foreach ($data as $key => $value) {
                $data[$key]['avatar'] = get_img_path($value['avatar']);
                $data[$key]['birthday'] = date('Y-m-d',$value['birthday']);
            }
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员卡挂失
     */
    public function loss()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (isset($getData['id']) && !empty($getData['id'])) {
                if (isset($getData['loss_content'])) {
                    $content = $getData['loss_content'];
                } else {
                    $content = '';
                }
                $update = Db::name('qt_viper_card')->where(['id' => $getData['id']])->update(['status' => '3', 'loss_content' => $content]);
                if ($update !== false) {
                    $this->result('更新成功', '', 200);
                }
                $this->result('更新失败', '', 204);
            } else {
                $this->result('缺少参数', '', 204);
            }
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 会员卡批量挂失
     */
    public function lossAll()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (isset($getData['ids']) && !empty($getData['ids'])) {
                $ids = explode(',', $getData['ids']);
                foreach ($ids as $key => $value) {
                    Db::name('qt_viper_card')->where(['id' => $value])->update(['status' => '3']);
                }
                $this->result('更新成功', '', 200);
            } else {
                $this->result('缺少参数', '', 204);
            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员卡撤销挂失
     */
    public function close()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id']) || empty($getData['pass']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            $card = Db::name('qt_viper_card')->field('id,passwd,salt')->where('id', $getData['id'])->find();
            // 密码
            if ($getData['type'] == '1') {
                $newPasswd = pwd($getData['pass'], $card['salt']);
                if ($newPasswd == $card['passwd']) {
                    Db::name('qt_viper_card')->where(['id' => $getData['id']])->update(['status' => '1']);
                    $this->result('操作成功', '', 200);
                }
                $this->result('密码错误', '', 204);
            }
            if ($getData['type'] == '2') {
                if ($getData['pass'] != '123456') {
                    $this->result('验证码错误', '', 204);
                }
                Db::name('qt_viper_card')->where(['id' => $getData['id']])->update(['status' => '1']);
                $this->result('操作成功', '', 200);
            }
            $this->result('无效的参数', '', 204);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 开启或关闭会员短息提醒
     */
    public function openSms()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            $cardIds = Db::name('qt_viper_card')->where('viper_type_id', $getData['viper_type_id'])->column('id');
            $update = [];
            //开启
            if ($getData['type'] == '1') {
                $status = '1';
            } else {
                $status = '0';
            }
            foreach ($cardIds as $key => $value) {
                $update[$key]['id'] = $value;
                $update[$key]['is_receiver_message'] = $status;
            }
            $cardModel = new ViperCardModel();
            $cardModel->saveAll($update);
            $this->result('操作成功', '', 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 清空会员积分
     */
    public function clear()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id']) || empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $cardIds = Db::name('qt_viper_card')->where('viper_type_id', $getData['viper_type_id'])->column('id');
            $update = [];
            foreach ($cardIds as $key => $value) {
                $update[$key]['id'] = $value;
                $update[$key]['score'] = '0';
            }
            $cardModel = new ViperCardModel();
            $cardModel->saveAll($update);
            $this->result('操作成功', '', 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 补录会员卡
     */
    public function supplement()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\ViperCard();
            if (!$validate->scene('supplement')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $cardRes = Db::name('qt_viper_card')->where(['card_no' => $getData['card_no'], 'name' => $getData['name']])->find();
            if (empty($cardRes)) {
                try{
                    if(!empty($getData['birthday'])){
                        $birthday = strtotime($getData['birthday']);
                    }else{
                        $birthday = null;
                    }
                    Db::startTrans();
                    //没有会员卡新开一张
                    $getData['card_no'] = $getData['new_card_no'];
                    $getData['create_time'] = time();
                    $getData['birthday'] = $birthday;
                    $getData['store_id'] = $this->userInfo['store_id'];
                    $cardID = Db::name('qt_viper_card')->insertGetId($getData);
                    //插入记录
                    $log['card_id'] = $cardID;
                    $log['new_card_no'] = $getData['new_card_no'];
                    $log['viper_type_id'] = $getData['viper_type_id'];
                    $log['money'] = $getData['amount'];
                    $log['give_money'] = 0;
                    $log['user_id'] = $this->userInfo['id'];
                    $log['create_time'] = time();
                    Db::name('qt_viper_card_supplement')->insert($log);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('操作失败','',204);
                }
                $this->result('操作成功', '', 200);
            }else{
                if(!empty($getData['birthday'])){
                    $birthday = strtotime($getData['birthday']);
                }else{
                    $birthday = null;
                }
                $update = [
                    'card_no' => $getData['new_card_no'],
                    'mobile' => $getData['mobile'],
                    'gender' => $getData['gender'],
                    'birthday' =>  $birthday,
                    'viper_type_id' => $getData['viper_type_id'],
                    'is_receiver_message' => $getData['is_receiver_message'],
                    'neima' => $getData['neima'],
                ];
                try{
                    Db::startTrans();
                    Db::name('qt_viper_card')->where('id', $cardRes['id'])->update($update);
                    //插入记录
                    $log['card_id'] = $cardRes['id'];
                    $log['new_card_no'] = $getData['new_card_no'];
                    $log['viper_type_id'] = $getData['viper_type_id'];
                    $log['money'] = $getData['amount'];
                    $log['give_money'] = 0;
                    $log['user_id'] = $this->userInfo['id'];
                    $log['create_time'] = time();
                    Db::name('qt_viper_card_supplement')->insert($log);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('操作失败','',204);
                }
                $this->result('操作成功', '', 200);
            }
        }
    }


    /**
     * 会员转账查询
     */
    public function giro_search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['type']) || empty($getData['number'])) {
                $this->result('缺少参数！', '', 204);
            }
            //类型 1 手机号 2 卡号 3 内码
            if ($getData['type'] == '1') {
                $where[] = ['mobile', 'like', '%' . $getData['number'] . '%'];
            }
            if ($getData['type'] == '2') {
                $where[] = ['card_no', 'eq', $getData['number']];
            }
            if ($getData['type'] == '3') {
                $where[] = ['neima', 'eq', $getData['number']];
            }
            $data = Db::name('qt_viper_card')
                ->alias('vc')
                ->leftJoin('qt_viper_type t', 'vc.viper_type_id = t.id')
                ->field('vc.id as card_id ,vc.mobile,vc.card_no,vc.amount,vc.give_amount,t.name as type_name')
                ->where($where)
                ->where(['vc.status'=>'1'])
                ->find();
            $this->result('查询成功', $data, 200);
        }
    }


    /**
     * 会员转账
     */
    public function giro()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['card_id']) || empty($getData['new_card_id']) || empty($getData['passwd'])) {
                $this->result('缺少参数！', '', 204);
            }
            if(empty($getData['amount']))$getData['amount'] = 0;
            if(empty($getData['give_amount']))$getData['give_amount'] = 0;

            $oldCardRes = Db::name('qt_viper_card')->where('id', $getData['card_id'])->find();
            $newCardRes = Db::name('qt_viper_card')->where('id', $getData['new_card_id'])->find();
            if ($getData['amount'] > $oldCardRes['amount']) {
                $this->result('转出金额超过卡内余额！', '', 204);
            }
            if ($getData['give_amount'] > $oldCardRes['give_amount']) {
                $this->result('转出赠送金额超过卡内赠送余额！', '', 204);
            }
            //判断密码
            if ($getData['type'] == '1') {
                if (empty($oldCardRes['passwd'])) {
                    $this->result('会员卡暂未设置密码！', '', 204);
                }
                $passwd = pwd($getData['passwd'], $oldCardRes['salt']);
                if ($passwd != $oldCardRes['passwd']) {
                    $this->result('密码不正确！', '', 204);
                }
            }
            //验证码
            if ($getData['type'] == '2') {
                if ($getData['passwd'] != '123456') {
                    $this->result('验证码错误', '', 204);
                }
            }
            $giroData = [
                'store_id' => $this->userInfo['store_id'],
                'user_id' => $this->userInfo['id'],
                'old_card_id' => $getData['card_id'],
                'old_amount' => $oldCardRes['amount'],
                'old_give_amount' => $oldCardRes['give_amount'],
                'new_card_id' => $getData['new_card_id'],
                'new_amount' => $newCardRes['amount'],
                'new_give_amount' => $newCardRes['give_amount'],
                'amount' => $getData['amount'],
                'give_amount' => $getData['give_amount'],
                'create_time' => time(),
            ];
            //插入变更记录
            $oldData[0] = [
                'viper_card_id' => $oldCardRes['viper_user_id'],
                'type' => '2',
                'money' => $getData['amount'],
                'create_time' => time(),
                'check' => '2',
                'flag' => '1',
                'after_money' => $oldCardRes['amount'] - $getData['amount'],

            ];
            $oldData[1] = [
                'viper_card_id' => $oldCardRes['viper_user_id'],
                'type' => '2',
                'money' => $getData['give_amount'],
                'create_time' => time(),
                'check' => '2',
                'flag' => '3',
                'after_money' => $oldCardRes['give_amount'] - $getData['give_amount'],

            ];
            //新用户记录
            $oldData[2] = [
                'viper_card_id' => $newCardRes['viper_user_id'],
                'type' => '2',
                'money' => $getData['amount'],
                'create_time' => time(),
                'check' => '1',
                'flag' => '1',
                'after_money' => $newCardRes['amount'] + $getData['give_amount'],

            ];
            $oldData[3] = [
                'viper_card_id' => $newCardRes['viper_user_id'],
                'type' => '2',
                'money' => $getData['give_amount'],
                'create_time' => time(),
                'check' => '1',
                'flag' => '3',
                'after_money' => $newCardRes['give_amount'] + $getData['give_amount'],

            ];
            //老用户
            $oldAmount = $oldCardRes['amount'] - $getData['amount'];
            $oldGiveAmount = $oldCardRes['give_amount'] - $getData['give_amount'];
            //新用户
            $newAmount = $newCardRes['amount'] + $getData['amount'];
            $newGiveAmount = $newCardRes['give_amount'] + $getData['give_amount'];
            //数据库操作
            try {
                Db::startTrans();
                //插入记录
                Db::name('qt_viper_card_giro')->insert($giroData);
                //插入日志记录
                Db::name('qt_viper_money_log')->insertAll($oldData);
                //更新老用户
                Db::name('qt_viper_card')->where('id', $getData['card_id'])->update(['amount' => $oldAmount, 'give_amount' => $oldGiveAmount]);
                Db::name('qt_viper_card')->where('id', $getData['card_id'])->setDec('total_amount',$getData['amount']);
                Db::name('qt_viper_card')->where('id', $getData['card_id'])->setDec('give_total_amount',$getData['give_amount']);
                //更新新用户
                Db::name('qt_viper_card')->where('id', $getData['new_card_id'])->update(['amount' => $newAmount, 'give_amount' => $newGiveAmount]);
                Db::name('qt_viper_card')->where('id', $getData['new_card_id'])->setInc('total_amount',$getData['amount']);
                Db::name('qt_viper_card')->where('id', $getData['new_card_id'])->setInc('give_total_amount',$getData['give_amount']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转账失败', '', 204);
            }
            $this->result('转账成功', '', 200);
        }
    }


    /**
     * 会员生日提醒
     */
    public function birthday()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->post('limit');
            $moth = date('m');
            $day = date('d');
            $number = $moth . $day;
            $card = Db::name('qt_viper_card')
                ->field('id,card_no,mobile,name,gender,birthday,viper_type_id')
                ->where('birthday_number', '>', $number)
                ->where('store_id', $this->userInfo['store_id'])
                ->where(['is_receiver_message' => '1'])
                ->paginate($limit)
                ->each(function ($item) {
                    $birthMoth = date('m-d', $item['birthday']);
                    $birthday = date('Y') . '-' . $birthMoth;
                    $item['time'] = CommonService::getBetweenDayNum($birthday, date("Y-m-d"));
                    $item['type_name'] = Db::name('qt_viper_type')->where('id', $item['viper_type_id'])->value('name');
                    return $item;
                });
            $this->result('查询成功', $card, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员异常使用
     */
    public function error_card()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->post('limit');
            $sql = Db::name('qt_viper_card')
                ->alias('vc')
                ->leftJoin('qt_viper_type t', 'vc.viper_type_id = t.id')
                ->field('vc.id,vc.mobile,vc.name,t.name as type_name,vc.status,vc.error_content')
                ->where('vc.status', '2')
                ->where('vc.store_id', $this->userInfo['store_id']);
            //时间筛选
            if (isset($data['start_time']) && !empty($page['start_time'])) {
                $sql = $sql->whereTime('vc.update_time', '>', strtotime($data['start_time']));
            }
            if (isset($data['end_time']) && !empty($page['end_time'])) {
                $sql = $sql->whereTime('vc.update_time', '<', strtotime($data['start_time']));
            }
            if (isset($getData['start_time']) && !empty($getData['start_time']) && isset($getData['end_time']) && !empty($getData['end_time'])) {
                $start_time = strtotime($getData['start_time']);
                $end_time = strtotime($getData['end_time']);
                $sql = $sql->whereBetweenTime('vc.update_time', $start_time, $end_time);
            }
            $card = $sql->paginate($limit);
            $this->result('查询成功', $card, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员异常使用条件保存添加
     */
    public function error_where_save()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\ViperCardError();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            if (empty($getData['id'])) {
                //添加
                $getData['create_time'] = time();
                $insert = Db::name('qt_viper_card_error')->insert($getData);
                if ($insert) {
                    $this->result('添加成功', '', 200);
                }
                $this->result('添加失败', '', 204);
            } else {
                //修改
                $update = Db::name('qt_viper_card_error')->where('id', $getData['id'])->update($getData);
                if ($update !== false) {
                    $this->result('修改成功', '', 200);
                }
                $this->result('修改失败', '', 204);
            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 异常条件获取
     */
    public function error_where_edit()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_viper_card_error')
                ->field('id,hour,number,cashier_number,engineer_number')
                ->where('store_id', $this->userInfo['store_id'])
                ->find();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 开票数据
     */
    public function open_list()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $sql = ViperCardModel::alias('v')
            ->field('v.id,v.name as user_name,v.mobile,v.card_no,v.gender,t.name as type_name')
            ->leftJoin('dp_qt_viper_type t', 't.id=v.viper_type_id')
            ->where(['v.store_id' => $this->userInfo['store_id']]);
        //手机号搜索
        if (isset($data['mobile']) && !empty($data['mobile'])) {
            $sql = $sql->where(['v.mobile' => $data['mobile']]);
        }
        //卡号搜索
        if (isset($data['card_no']) && !empty($data['card_no'])) {
            $sql = $sql->where(['v.card_no' => $data['card_no']]);
        }
        $resultData = $sql->paginate($data['limit'])
            ->each(function ($item) {
                $already = Db::name('qt_viper_card_recharge_log')
                    ->where(['viper_card_id' => $item['id'], 'pay_status' => '1', 'status' => '2'])
                    ->sum('amount');
                $item['already_open'] = $already;
            });
        $this->result('查询成功', $resultData, 200);
    }


    /**
     * 会员充值详情
     */
    public function open_detail()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $already = Db::name('qt_viper_card_recharge_log')
            ->field('l.id,l.status,l.pay_status,s.name as store_name,t.id as template_id,t.name as template_name,l.create_time,l.integral,l.amount,l.give_amount,l.status,u.real_name')
            ->alias('l')
            ->leftJoin('qt_store s ', 's.id = l.store_id')
            ->leftJoin('qt_viper_recharge_template t ', 't.id = l.recharge_tempid')
            ->leftJoin('qt_users u ', 'u.id = l.creater')
            ->where(['l.viper_card_id' => $data['id'], 'l.pay_status' => '1', 'l.card_type' => '1'])
            ->paginate($data['limit'])->each(function ($item) {
                $item['return_money'] = '';
                $content = Db::name('qt_viper_recharge_template_return')
                    ->field('amount,times')
                    ->where('template_id', $item['template_id'])
                    ->select();
                if (!empty($content)) {
                    foreach ($content as $key => $value) {
                        $returnMoney[$key] = '第' . $value['times'] . '个月' . '返还' . $value['amount'] . '元';
                    }
                    $item['return_money'] = implode(',', $returnMoney);
                }
                return $item;
            });
        $this->result('查询成功', $already, 200);
    }


    /**
     * 会员充值详情开票
     */
    public function open_billing()
    {
        $data = $this->request->post();
        if (!isset($data['id']) || empty($data['id'])) {
            $this->result('缺少参数', '', 204);
        }
        if ($data['type'] == '1') {
            //开票
            $update['status'] = '2';
            $update['open_user'] = $this->userInfo['id'];
            $update['open_content'] = $data['open_content'];
            $update['open_time'] = time();
        }
        if ($data['type'] == '2') {
            //撤销接口
            $update['status'] = '1';
            $update['open_user'] = '';
        }
        $already = Db::name('qt_viper_card_recharge_log')->where(['id' => $data['id']])->update($update);
        if ($already !== false) {
            $this->result('操作成功', '', 200);
        }
        $this->result('操作失败', '', 204);
    }


    /**
     * 会员开票详情
     */
    public function open_already()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $sql = Db::name('qt_viper_card_recharge_log')
            ->field('l.id,c.name as card_name,c.mobile,s.name as store_name,t.name as template_name,l.open_time,l.amount,u.real_name,l.open_content,l.amount,l.give_amount')
            ->alias('l')
            ->leftJoin('qt_store s ', 's.id = l.store_id')
            ->leftJoin('qt_viper_card c ', 'l.viper_card_id = c.id')
            ->leftJoin('qt_viper_recharge_template t ', 't.id = l.recharge_tempid')
            ->leftJoin('qt_users u ', 'u.id = l.open_user')
            ->where(['l.store_id' => $this->userInfo['store_id'], 'l.status' => '2', 'l.card_type' => '1']);
        //手机号搜索
        if (isset($data['mobile']) && !empty($data['mobile'])) {
            $sql = $sql->where(['c.mobile' => $data['mobile']]);
        }
        //卡号搜索
        if (isset($data['card_no']) && !empty($data['card_no'])) {
            $sql = $sql->where(['c.card_no' => $data['card_no']]);
        }
        //时间筛选
        if (isset($data['start_time']) && !empty($page['start_time'])) {
            $sql = $sql->whereTime('l.open_time', '>', strtotime($data['start_time']));
        }
        if (isset($data['end_time']) && !empty($page['end_time'])) {
            $sql = $sql->whereTime('l.open_time', '<', strtotime($data['start_time']));
        }
        if (isset($getData['start_time']) && !empty($getData['start_time']) && isset($getData['end_time']) && !empty($getData['end_time'])) {
            $start_time = strtotime($getData['start_time']);
            $end_time = strtotime($getData['end_time']);
            $sql = $sql->whereBetweenTime('l.open_time', $start_time, $end_time);
        }


        $already = $sql->paginate($data['limit']);
        $this->result('查询成功', $already, 200);
    }


    /**
     * 会员时段列表
     * mobile  card_no
     */
    public function time_lists()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $sql = DB::name('qt_viper_card_recharge_log')
            ->alias('l')
            ->field('l.id,c.name as user_name,c.card_no,t.name as type_name,c.expire,c.card_amount')
            ->leftJoin('dp_qt_viper_card c', 'c.id=l.viper_card_id')
            ->leftJoin('dp_qt_viper_type t', 't.id=c.viper_type_id')
            ->leftJoin('dp_qt_user_viper uv', 'uv.id=l.user_id')
            ->where(['v.store_id' => $this->userInfo['store_id']]);
        //手机号搜索
        if (isset($data['mobile']) && !empty($data['mobile'])) {
            $sql = $sql->where(['v.mobile' => $data['mobile']]);
        }
        //卡号搜索
        if (isset($data['card_no']) && !empty($data['card_no'])) {
            $sql = $sql->where(['v.card_no' => $data['card_no']]);
        }
        //卡类型
        if (isset($data['viper_type_id']) && !empty($data['viper_type_id'])) {
            $sql = $sql->where(['v.viper_type_id' => $data['viper_type_id']]);
        }
        //开卡时间
        if (isset($getData['start_create_time']) && !empty($getData['start_create_time']) && isset($getData['end_create_time']) && !empty($getData['end_create_time'])) {
            $start_time = strtotime($getData['start_birthday']);
            $end_time = strtotime($getData['end_birthday']);
            $sql = $sql->whereBetweenTime('v.create_time', $start_time, $end_time);
        }
        $list = $sql->paginate($data['limit'])->each(function ($item) {
            $item['avatar'] = get_img_path($item['avatar']);
        });
        $this->result('获取成功', $list, 200);
    }


    /**
     * 充值金额返还
     */
    public function recharge_return()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $data = Db::name('qt_viper_recharge_template_return')
                ->field('tr.id,tr.template_id,tr.create_time,tr.viper_type_id,t.name as type_name,u.real_name')
                ->alias('tr')
                ->leftJoin('qt_users u', 'u.id = tr.user_id')
                ->leftJoin('qt_viper_type t', 't.id = tr.viper_type_id')
                ->where('tr.store_id', $this->userInfo['store_id'])
                ->group('template_id')
                ->paginate($getData['limit'])
                ->each(function ($item) {
                    $template = Db::name('qt_viper_recharge_template')->where('id', $item['template_id'])->find();
                    $item['template_name'] = $template['name'];
                    $item['amount'] = $template['amount'];
                    $item['give_amount'] = $template['give_amount'];
                    $item['template_type'] = $template['type'];
                    $item['template_number'] = Db::name('qt_viper_recharge_template_return')->where('template_id', $item['template_id'])->count();
                    return $item;
                });
            $this->result('获取成功', $data, 200);
        }
    }


    /**
     * 充值金额返还明细
     */
    public function recharge_return_lists()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $data = Db::name('qt_viper_recharge_template_return')
                ->field('id,times,amount')
                ->where('template_id', $getData['template_id'])
                ->select();
            $this->result('获取成功', $data, 200);
        }
    }


    /**
     * 充值金额返还明细
     */
    public function recharge_return_delete()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $data = Db::name('qt_viper_recharge_template_return')
                ->where('template_id', $getData['template_id'])
                ->delete();
            $this->result('删除成功', $data, 200);
        }
    }

    /**
     * 更新手机号
     */
    public function change_phone()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['phone'])
                || empty($getData['viper_card_id'])
                || empty($getData['passwd'])
                || empty($getData['type'])

            ) {
                $this->result('缺少参数', '', 204);
            }

            $cardRes = Db::name('qt_viper_card')->where('id', $getData['viper_card_id'])->find();
            if ($getData['type'] == '1' && pwd($getData['passwd'], $cardRes['salt']) != $cardRes['passwd']) {//密码
                $this->result('密码错误', '', 204);
            }
            if ($getData['type'] == '2') {
                //验证码
                //$sms = new Smscm();
                //$checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 3);
                //if ($checkPhone['code'] == 200) {
                //}
                if ($getData['passwd'] != '123456') {
                    $this->result('验证码错误', '', 204);
                }

            }
            $insert = [
                'store_id' => $this->userInfo['store_id'],
                'user_id' => $this->userInfo['id'],
                'remarks_type' => '8',
                'content' => $getData['content'],
                'desc' => '',
                'create_time' => time(),
            ];
            try {
                Db::startTrans();
                //更新手机号
                Db::name('qt_viper_card')->where(['id' => $getData['viper_card_id']])->update(['mobile' => $getData['phone']]);
                //写手机号变更记录
                Db::name('qt_viper_card_phone_update')->insert([
                    'viper_card_id' => $getData['viper_card_id'],
                    'old_phone' => $cardRes['mobile'],
                    'new_phone' => $getData['phone'],
                    'create_time' => time(),
                    'creater' => $this->userInfo['id'],
                    'content' => $getData['content'],
                ]);
                //插入备注信息
                Db::name('qt_remarks_log')->insert($insert);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('修改失败:' . $exception->getMessage(), '', 204);
            }
            $this->result('修改成功', '', 200);

        }
    }


    /**
     * 修改密码（短信验证码）
     */
    public function save_phone()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['mobile']) || empty($getData['code']) || empty($getData['passwd']) || empty($getData['new_passwd'])) {
                $this->result('缺少参数', '', 204);
            }
            $cardId = Db::name('qt_viper_card')->where('mobile', $getData['mobile'])->find();
            if (empty($cardId)) {
                $this->result('会员卡不存在', '', 204);
            }
            $sms = new Smscm();
            $checkPhone['code'] = 200;
            //$checkPhone = $sms->check_smscode($getData['phone'], $getData['code'], 3);
            if ($checkPhone['code'] == 200) {
                $salt = number_rand('4');
                $newPass = pwd($getData['new_passwd'], $salt);
                $update = Db::name('qt_viper_card')
                    ->where('id', $cardId['id'])
                    ->update(['mobile' => $getData['mobile'], 'salt' => $salt, 'passwd' => $newPass]);
                if ($update) {
                    $this->result('密码修改成功', '', 200);
                }
            }
            $this->result('密码修改失败', '', 204);

        }
    }


    /**
     * 修改密码(密码)
     */
    public function save_pass()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['mobile']) || empty($getData['passwd']) || empty($getData['new_passwd'])) {
                $this->result('缺少参数', '', 204);
            }
            $cardId = Db::name('qt_viper_card')
                ->where('mobile', $getData['mobile'])
                ->whereOr('card_no', $getData['mobile'])
                ->find();
            if (empty($cardId)) {
                $this->result('会员卡不存在', '', 204);
            }
            $pass = pwd($getData['passwd'], $cardId['salt']);
            if ($pass != $cardId['passwd']) {
                $this->result('密码错误', '', 204);
            }
            $salt = number_rand('4');
            $newPass = pwd($getData['new_passwd'], $salt);
            $update = Db::name('qt_viper_card')
                ->where('id', $cardId['id'])
                ->update(['mobile' => $getData['mobile'], 'salt' => $salt, 'passwd' => $newPass]);
            if ($update) {
                $this->result('密码修改成功', '', 200);
            }
        }
    }


    /**
     * 获取会员卡时段余额
     * @return array
     */
    public function balance()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (!isset($getData['limit']) || empty($getData['limit'])) {
                $getData['limit'] = '10';
            }

            $sql = Db::name('qt_viper_card')
                ->alias('c')
                ->leftJoin('qt_viper_type t', 't.id = c.viper_type_id')
                ->field('c.id,c.card_no,t.name as type_name,c.name,c.create_time,c.amount,c.give_amount,c.score,c.mobile,c.expire')
                ->where(['c.store_id' => $userInfo['store_id']])
                ->order('c.id desc');
            //单号查询
            if (isset($getData['card_no']) && !empty($getData['card_no'])) {
                $sql = $sql->where('c.card_no', $getData['card_no']);
            }
            //时间查询
            if (isset($getData['start_time']) && !empty($getData['start_time'])) {
                $sql = $sql->whereTime('c.create_time', '>', strtotime($getData['start_time']));
            }
            if (isset($getData['end_time']) && !empty($getData['end_time'])) {
                $sql = $sql->whereTime('c.create_time', '<', strtotime($getData['start_time']));
            }
            //会员卡类型
            if (isset($getData['viper_type_id']) && !empty($getData['viper_type_id'])) {
                $sql = $sql->where('c.viper_type_id', $getData['viper_type_id']);
            }
            //会员卡类型
            if (isset($getData['type']) && !empty($getData['type'])) {
                if ($getData['type'] == '2') {
                    $sql = $sql->whereIn('c.status', ['1', '2']);
                }
            }
            $data = $sql->paginate($getData['limit'])->each(function ($item) {
                $end = Db::name('qt_viper_card_recharge_log')->where('viper_card_id', $item['id'])->order('id desc')->find();
                if ($end['create_time'] > $item['create_time']) {
                    $item['end_time'] = $end['create_time'];
                    $item['end_count'] = count($end);
                    $item['end_amount'] = $end['amount'];
                } else {
                    $item['end_time'] = '';
                    $item['end_count'] = '';
                    $item['end_amount'] = '';
                }
                $consumption = Db::name('qt_check_out')->where('viper_card_id', $item['id'])->order('id desc')->find();
                if ($consumption['cashier_time'] > $item['create_time']) {
                    $item['consumption_time'] = $consumption['cashier_time'];
                    $item['consumption_count'] = count($consumption);
                } else {
                    $item['consumption_time'] = '';
                    $item['consumption_count'] = '';
                }
                return $item;
            });
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改会员信息
     */
    public function editCard()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_card_id'])) {
                $this->result('缺少会员卡ID', '', 204);
            }
            if (!empty($getData['birthday'])) {
                $getData['birthday'] = strtotime($getData['birthday']);
            }
            $getData['update_time'] = time();
            unset($getData['create_time']);
            $update = Db::name('qt_viper_card')->where(['id' => $getData['viper_card_id']])->update($getData);
            if ($update !== false) {
                $this->result('更新成功', '', 200);
            } else {
                $this->result('更新失败', '', 204);
            }
        }
    }


    /**
     * 删除会员信息
     */
    public function delCard()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_card_id'])) {
                $this->result('缺少会员卡ID', '', 204);
            }
            $viperCard = Db::name('qt_viper_card')->where(['id' => $getData['viper_card_id']])->find();
            if ($viperCard['amount'] > 0) {
                $this->result('无法注销有余额的会员卡', '', 204);
            }
            $del = Db::name('qt_viper_card')->where(['id' => $getData['viper_card_id']])->update(['status' => '4']);
            if ($del) {
                $this->result('删除成功', '', 200);
            } else {
                $this->result('删除失败', '', 204);
            }
        }
    }


    /**
     * 消费明细
     */
    public function consume_detail()
    {
        $post = $this->request->post();
        $limit = !empty($post['limit']) ? $post['limit'] : 10;
        if (empty($post['user_id'])) {
            $this->result('会员ID不能为空', '', 204);
        }

        $query = Db::name('qt_check_out_pay')
            ->alias('pay')
            ->field([
                'out.store_id',//会员所在门店
                'out.order_no',//结账单号
                'out.cashier_time',//结账时间
                'out.cashier_id',//结账人
                //'out.cashier_id',//积分
                'out.order_type',//订单状态
                'out.pay_content',//支付内容
                'out.viper_card_id',//会员卡ID
                'pay.pay_money as total_money'
            ])
            ->leftJoin("qt_check_out out", 'pay.check_out_id=out.id')
            ->leftJoin("qt_viper_card card", 'card.id=out.viper_card_id')
            ->leftJoin('qt_viper_type type', 'card.viper_type_id=type.id')
            ->where('out.store_id', $this->userInfo['store_id'])
            ->where(['pay.viper_card_id'=> $post['user_id'],'pay.type'=>'2']);

        $list = $query->order('out.id desc')->paginate($limit)->each(function ($item) {
            //$item['pay_content'] = '[{"pay_type":"微信","pay_money":100},{"pay_type":"支付宝","pay_money":111}]';

            $item['cashier_name'] = Db::name('qt_users')->where('id', $item['cashier_id'])->value('real_name');
            $pay_content_json = json_decode($item['pay_content'], true);
            if (!empty($pay_content_json)) {
                $item['pay_content'] = implode(',', array_column($pay_content_json, 'pay_type'));
            }
            $order_type = [1 => '正常订单', 2 => '挂账单'];
            $item['order_type'] = $order_type[$item['order_type']];
            $item['store_name'] = Db::name('qt_store')->where('id', $item['store_id'])->value('name');
            $item['card_no'] = Db::name('qt_viper_card')->where('id', $item['viper_card_id'])->value('card_no');
            $item['money_log'] = Db::name('qt_viper_money_log')
                ->where('id', $item['order_no'])
                ->where(['type' => 1, 'check' => 1, 'flag' => 3,])
                ->value('money');
            return $item;
        });
        $this->result('查询成功', $list, 200);
    }


    /**
     * 充值明细
     */
    public function invest_detail()
    {
        $post = $this->request->post();
        $limit = !empty($post['limit']) ? $post['limit'] : 10;
        if (empty($post['viper_card_id'])) {
            $this->result('会员卡ID不能为空', '', 204);
        }

        $query = Db::name('qt_viper_card_recharge_log')->alias('log')
            ->field([
                'log.id',
                'log.pay_status',//支付状态 0 未支付 1 正常 3 已撤销
                'log.create_time',
                'log.integral',
                'log.card_amount',
                'log.amount',
                'log.card_type',
                'log.store_id',
                'log.recharge_tempid',
                'log.viper_card_id',
                'log.recharge_tempid',
                'user.real_name',
                'log.is_revoke',
                'log.give_amount',
                'log.recharge_temp_name',
                'log.after_money',
            ])
            ->leftJoin('qt_viper_card cid', 'cid.id=log.viper_card_id')
            ->leftJoin('qt_users user', 'user.id = log.creater');
        $query->where('log.viper_card_id', $post['viper_card_id'])
            ->where('log.store_id', $this->userInfo['store_id']);
        $list = $query->order('log.id desc')->paginate($limit)->each(function ($item) {
            $item['store_name'] = $this->storeInfo['name'];
            $temp_data = [
                'template_name' => '',
                'template_item' => '',
            ];
            if ($item['card_type'] == 1) {//普通卡
                if($item['recharge_tempid'] == '0'){
                    $temp_data['template_name'] = '';
                    $temp_data['template_item'] = '';
                }else{
                    $template = ViperCardService::getTemplate($item['store_id'], $item['recharge_tempid']);
                    if (!empty($template)) {
                        $temp_data['template_name'] = $template[0]['name'];
                        $temp_data['template_item'] = '';
                    }
                }

            }
            if ($item['card_type'] == 2) {//次卡
                $template = ViperCardService::getNumberTemplate($item['store_id'], $item['recharge_tempid']);
                if (!empty($template)) {
                    $template_data = $template[0];
                    $temp_data['template_name'] = $template_data['name'];
                    $item_list = array_column($template_data['item_list'], 'name');
                    $temp_data['template_item'] = implode(',', $item_list);
                }
            }
            if ($item['card_type'] == 3) {//月卡
                $template = ViperCardService::getMonthTemplate($item['store_id'], $item['recharge_tempid']);
                $template_data = $template[0];
                $temp_data['template_name'] = $template_data['name'];
                $item_list = array_column($template_data['item_list'], 'name');
                $temp_data['template_item'] = implode(',', $item_list);
            }
            if ($item['card_type'] == 4) {//按照实际金额充值
                $temp_data['template_name'] = $item['recharge_temp_name'];
            }
            $item['temp_data'] = $temp_data;
            return $item;
        });

        $this->result('查询成功', $list, 200);


    }

    /**
     * 返还明细
     */
    public function return_detail()
    {
        $viper_card_id = $this->request->post('viper_card_id', 0);
        $limit = $this->request->post('limit', 10);
        if (empty($viper_card_id)) {
            $this->result('会员卡ID不能为空', '', 204);
        }
        $query = Db::name('qt_viper_card_return')->where(['viper_card_id' => $viper_card_id]);
        $data_list = $query->order('id desc')->paginate($limit)->each(function ($item) {
            $item['is_return'] = $item['is_return'] == 1 ? '未返还' : '已返还';
            $item['return_time'] = date('Y-m-d H:i:s', $item['return_time']);
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            return $item;
        });

        $this->result('查询成功', $data_list, 200);
    }

    /**
     * 退款明细
     */
    public function refund_detail()
    {


    }

    /**
     * 积分修改明细
     */
    public function integral_update_detail()
    {


    }

    /**
     * 积分兑换明细
     */
    public function integral_exchange_detail()
    {
        $viper_card_id = $this->request->post('viper_card_id', 0);
        $limit = $this->request->post('limit', 10);
        if (empty($viper_card_id)) {
            $this->result('会员卡ID不能为空', '', 204);
        }
        $query = Db::name('qt_viper_integral_log')->alias('log')
            ->field([
                'log.*',
                'exc.name',
            ])
            ->leftJoin('qt_viper_integral_exchange exc', 'log.integral_id=exc.id')
            ->where(['log.viper_card_id' => $viper_card_id])
            ->order('log.id desc')
            ->paginate($limit);
        $data_list = $query->each(function ($item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            $item['user_name'] = Db::name('qt_users')->where('id', $item['user_id'])->value('real_name');

            return $item;
        });

        $this->result('查询成功', $data_list, 200);
    }


    /**
     * 转账明细
     */
    public function transfer_detail()
    {
        $viper_card_id = $this->request->post('viper_card_id', 0);
        $limit = $this->request->post('limit', 10);
        if (empty($viper_card_id)) {
            $this->result('会员卡ID不能为空', '', 204);
        }
        $query = Db::name('qt_viper_card_giro')
            ->field('giro.*,store.name as store_name,card.name as card_name,card.mobile,card.card_no')
            ->alias('giro')
            ->leftJoin('qt_store store','store.id = giro.store_id')
            ->leftJoin('qt_viper_card card','card.id = giro.old_card_id')
            ->where('giro.store_id', $this->userInfo['store_id'])
            ->where('giro.old_card_id', $viper_card_id);
        $list = $query->paginate($limit)->each(function ($item) {
            $newCardData = Db::name('qt_viper_card')
                ->field('card.id,card.name,card.mobile,card.card_no,store.name as store_name')
                ->alias('card')
                ->leftJoin('qt_store store','store.id = card.store_id')
                ->where(['card.id'=>$item['new_card_id']])->find();
            $item['new_card_name'] = $newCardData['name'];
            $item['new_card_mobile'] = $newCardData['mobile'];
            $item['new_card_no'] = $newCardData['card_no'];
            $item['new_store_name'] = $newCardData['store_name'];
            $item['user_name'] = Db::name('qt_users')->where('id', $item['user_id'])->value('real_name');
            return $item;
        });

        $this->result('查询成功', $list, 200);
    }

    /**
     * 次卡月卡使用明细
     */
    public function card_use_detail()
    {
        $viper_card_id = $this->request->post('viper_card_id', 0);
        $limit = $this->request->post('limit', 10);
        if (empty($viper_card_id)) {
            $this->result('会员卡ID不能为空', '', 204);
        }
        $query = Db::name('qt_viper_card_item')->alias('item')
            ->field([
                'item.*',
                'log.create_time'
            ])
            ->leftJoin('qt_viper_card card', 'item.viper_card_id=card.id')
            ->leftJoin('qt_viper_card_recharge_log log', 'item.recharge_log_id=log.id')
            ->where('card.store_id', $this->userInfo['store_id'])
            ->whereNull('recharge_template_id')
            ->where('item.viper_card_id', $viper_card_id)
            ->where('item.status','neq', '3');
        $list = $query->paginate($limit)->each(function ($item) {
            $item['template_item'] = [];
            if (!empty($item['month_template_id']) && $item['month_template_id'] !== '0') {
                if($item['create_time'] == null){
                    $item['create_time']  = Db::name('qt_viper_card_number_supplement')
                        ->where(['viper_card_id'=>$item['viper_card_id'],'business_type'=>'2','template_id'=>$item['month_template_id']])
                        ->value('create_time');
                }

                $item['card_type'] = 1;
                $template = ViperCardService::getMonthTemplate($this->userInfo['store_id'], $item['month_template_id']);
                if (!empty($template)) {
                    $template_data = $template[0];
                    $item_list = array_column($template_data['item_list'], 'name');
                    $item['template_item'] = implode(',', $item_list);
                    //有效期
                    $time =( $template[0]['expire'] * 86400) + $item['create_time'];
                    $item['expire_time'] = ST($time);
                }

            }
            if (!empty($item['number_template_id'])) {
                $item['card_type'] = 2;
                if($item['create_time'] == null){
                    $item['create_time']  = Db::name('qt_viper_card_number_supplement')
                        ->where(['viper_card_id'=>$item['viper_card_id'],'business_type'=>'1','template_id'=>$item['number_template_id']])
                        ->value('create_time');
                }
                $template = ViperCardService::getNumberTemplate($this->userInfo['store_id'], $item['number_template_id']);
                if (!empty($template)) {
                    $template_data = $template[0];
                    $item_list = array_column($template_data['item_list'], 'name');
                    $item['template_item'] = implode(',', $item_list);
                    //有效期
                    $time =( $template[0]['expire'] * 86400) + $item['create_time'];
                    $item['expire_time'] = ST($time);
                }
            }
            return $item;
        });

        $this->result('查询成功', $list, 200);
    }

    /**
     * 手机变更明细
     */
    public function phone_update_detail()
    {

        $viper_card_id = $this->request->post('viper_card_id', 0);
        $limit = $this->request->post('limit', 10);
        if (empty($viper_card_id)) {
            $this->result('会员卡ID不能为空', '', 204);
        }
        $query = Db::name('qt_viper_card_phone_update')->alias('phone')
            ->field([
                'phone.*',
                'card.store_id',
            ])
            ->leftJoin('qt_viper_card card', 'card.id=phone.viper_card_id')
            ->where('card.store_id', $this->userInfo['store_id'])
            ->where('phone.viper_card_id', $viper_card_id);
        $list = $query->paginate($limit)->each(function ($item) {

            $item['user_name'] = Db::name('qt_viper_card')->where('id', $item['viper_card_id'])->value('name');
            $item['creater_name'] = Db::name('qt_users')->where('id', $item['creater'])->value('real_name');
            $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
            return $item;
        });

        $this->result('查询成功', $list, 200);
    }


    /**
     * 三方平台
     */
    public function tripartite()
    {


    }


    /**
     * 修改会员积分
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit_integral()
    {
        $getData = $this->request->post();
        if (empty($getData['id'])) {
            $this->result('缺少会员卡', '', 204);
        }
        $update = Db::name('qt_viper_card')->where(['id' => $getData['id']])->update(['score' => $getData['number']]);
        if ($update !== false) {
            $this->result('修改成功', '', 200);
        } else {
            $this->result('修改失败', '', 204);
        }
    }

    /**
     * 重置会员密码
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function reset_password()
    {
        $getData = $this->request->post();
        if (empty($getData['id'])) {
            $this->result('缺少会员卡', '', 204);
        }
        $viperCardData = Db::name('qt_viper_card')->where(['id' => $getData['id']])->find();
        $passwd = pwd(config('default_passwd'), $viperCardData['salt']);
        $update = Db::name('qt_viper_card')->where(['id' => $getData['id']])->update(['passwd' => $passwd]);
        if ($update !== false) {
            $this->result('重置成功', '', 200);
        } else {
            $this->result('重置失败', '', 204);
        }
    }


    /**
     * 领取会员卡实体卡
     */
    public function receive_card()
    {
        $getData = $this->request->post();
        $rule = [
            'id' => 'require',
            'mobile' => 'require',
            'type' => 'require',
            'code' => 'require',
            'card_no' => 'require',
            'neima' => 'require',
        ];
        $msg = [
            'id.require' => '缺少会员卡ID',
            'mobile.require' => '缺少手机号',
            'mobile.mobile' => '手机号不正确',
            'type.require' => '请选择验证类型',
            'code.require' => '密码或者验证码不正确',
            'card_no.require' => '卡号必须填写',
            'neima.require' => '卡内码必须填写',
        ];
        $validate = Validate::make($rule, $msg);
        $result = $validate->check($getData);
        if (!$result) {
            $this->result($validate->getError(), '', 204);
        }
        $viperCardData = Db::name('qt_viper_card')->where(['id' => $getData['id']])->find();
        //验证类型 1 密码 2 验证码
        if ($getData['type'] == '1') {
            $passwd = pwd($getData['code'], $viperCardData['salt']);
            if ($passwd != $viperCardData['passwd']) {
                $this->result('密码错误', '', 204);
            }
        }
        if ($getData['type'] == '2') {
            $check = new Alisms();
            $result = $check->check_smscode($getData['mobile'], $getData['code'], 3);
            if ($result['code'] != '200') {
                $this->result('短信验证失败', '', 204);
            }
        }
        $update = Db::name('qt_viper_card')->where(['id' => $getData['id']])->update([
            'card_no' => $getData['card_no'],
            'neima' => $getData['neima'],
            'bind_status' => '1'
        ]);
        if ($update !== false) {
            $this->result('领取成功', '', 200);
        } else {
            $this->result('领取失败', '', 204);
        }
    }


    /**
     * 检测会员卡是否含有次卡月卡
     */
    public function checkNumberMonth(){
        $getData = $this->request->post();
        if (empty($getData['viper_card_id'])) {
            $this->result('缺少会员卡', '', 204);
        }
        $data['number'] = false;
        $data['month'] = false;
        $number = Db::name('qt_viper_card_item')
            ->where(['viper_card_id'=>$getData['viper_card_id'],'status'=>'1'])
            ->whereNotNull('number_template_id')
            ->find();
        if($number != null){
            $data['number'] = true;
        }
        $month = Db::name('qt_viper_card_item')
            ->where(['viper_card_id'=>$getData['viper_card_id'],'status'=>'1'])
            ->whereNotNull('month_template_id')
            ->find();
        if($month != null){
            $data['month'] = true;
        }
        $this->result('查询成功', $data, 200);
    }


}
